<template>
    <div class="coupon-container">
        <el-row :gutter="[20, 30]" class="coupon-grid">
            <el-col v-for="coupon in coupons" :key="coupon.id" :xs="24" :sm="12" :md="12" :lg="8" :xl="6"
                class="coupon-column">
                <div class="coupon-card" :class="{
                    'disabled': coupon.disabled,
                }">
                    <!-- 顶部装饰条 -->
                    <div class="decorative-strip"></div>

                    <div class="coupon-header">
                        <span class="title">{{ coupon.couponName }}</span>
                        <el-tag :color="coupon.statusColor" effect="dark" class="status-tag" size="small">
                            {{ coupon.status }}
                        </el-tag>
                    </div>

                    <div class="coupon-content">
                        <!-- 优惠信息显示 -->
                        <div v-if="coupon.couponType === 1" class="discount amount-type">
                            <div class="currency-symbol">¥</div>
                            <div class="main-amount">
                                <span class="amount">{{ coupon.discountAmount }}</span>
                                <div v-if="coupon.minAmount" class="condition">
                                    满{{ coupon.minAmount }}元可用
                                </div>
                            </div>
                        </div>
                        <div v-else-if="coupon.couponType === 2" class="discount rate-type">
                            <span class="rate">{{ (coupon.discountRate * 10).toFixed(1) }}</span>
                            <span class="rate-symbol">折</span>
                        </div>

                        <!-- 有效期 -->
                        <div class="valid-date">
                            <i class="el-icon-time"></i>
                            <span class="date-text">{{ coupon.endTime }}</span>
                        </div>
                    </div>

                    <div class="coupon-footer">
                        <el-progress :percentage="(1 - coupon.remaining / coupon.totalQuantity) * 100"
                            :color="progressColor(coupon)" :show-text="false" stroke-width="6"
                            v-if="coupon.remaining > 0" />
                        <el-button type="danger" :disabled="coupon.disabled || coupon.remaining === 0"
                            @click="handleGrab(coupon.id)" block class="grab-button">
                            {{ '立即领取' }}
                            <span v-if="coupon.remaining > 0" class="remaining-count">
                                (剩余{{ coupon.remaining }}张)
                            </span>
                        </el-button>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { getCartList, getCoupons, checkIsObtainCoupon } from '@/api/user/coupon';
export default {
    data() {
        return {
            coupons: [] // 从接口获取的数据
        }
    },
    created() {
        this.fetchCoupons();
    },
    methods: {
        async fetchCoupons() {
            try {
                const res = await getCartList(0);
                console.log(res.data.data);

                this.coupons = res.data.data.records
                // .map(item => ({
                //     ...item,
                //     // 添加前端需要的转换逻辑
                //     status: this.formatStatus(item.status),
                //     couponType: this.formatCouponType(item.couponType)
                // }));
                console.log('this.coupons', this.coupons);

            } catch (error) {
                console.error('获取优惠券失败', error);
            }
        },
        formatStatus(status) {
            const map = { 1: '进行中', 2: '未开始', 3: '已结束' };
            return map[status] || '未知状态';
        },
        formatCouponType(type) {
            const map = { 1: '满减券', 2: '折扣券', 3: '立减券' };
            return map[type] || '未知类型';
        },

        // 前端改造后的领取方法
        handleGrab(id) {
            // 显示加载状态
            this.loading = true;
            // 调用异步领取接口
            getCoupons(id).then(res => {
                if (res.data.code === 1) { // 异步处理中
                    this.startPolling(id);
                } else { // 立即返回结果
                    this.handleResult(res.data);
                }
            }).catch(error => {
                this.$message.error("请求失败");
                this.loading = false;
            });
        },

        // 启动轮询
        startPolling(taskId) {
            let retryCount = 0;
            const maxRetries = 3; // 最大尝试次数（30*2s=1分钟）
            const poll = () => {
                checkIsObtainCoupon(taskId).then(res => {
                    if (res.data.code === 1) {
                        this.$message.success(res.data.data);
                        this.loading = false;
                    } else if (res.data.code === 2) {
                        this.$message.error(res.data.msg || "领取失败");
                        this.loading = false;
                    } else if (retryCount < maxRetries) {
                        retryCount++;
                        setTimeout(poll, 2000); // 2秒后重试
                    } else {
                        this.$message.warning("请求超时，请稍后查看结果");
                        this.loading = false;
                    }
                }).catch(error => {
                    this.$message.error("状态查询失败");
                    this.loading = false;
                });
            };

            // 首次执行
            poll();
        },
        // 处理最终结果
        handleResult(data) {
            this.loading = false;
            if (data.code === 0) {
                this.$message.error(data.msg);
            } else {
                this.$message.success(data.msg);
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.coupon-container {
    padding: 30px;
    max-width: 1400px;
    margin: 0 auto;
    background-color: #f4f4f4;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
}

.mb-20 {
    margin-bottom: 20px;
}

.coupon-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    position: relative;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        animation: gentleVibrate 0.5s ease-in-out;
    }

    &.disabled {
        opacity: 0.6;
        filter: grayscale(100%);
        pointer-events: none;
    }
}

.decorative-strip {
    height: 8px;
    background: linear-gradient(90deg, #c5e1a5 0%, #81c784 100%);
}

.coupon-header {
    padding: 18px;
    background: #f0f9e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2px dashed #dcedc8;

    .title {
        font-size: 18px;
        font-weight: 700;
        color: #212121;
        letter-spacing: 0.5px;
    }

    .status-tag {
        border-radius: 4px;
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        padding: 4px 8px;
    }
}

.coupon-content {
    padding: 20px;
    text-align: center;
    position: relative;

    .discount {
        margin: 15px 0;

        &.amount-type {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .currency-symbol {
            font-size: 24px;
            color: #388e3c;
            font-weight: 600;
            transform: translateY(-2px);
        }

        .main-amount {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        .amount {
            font-size: 36px;
            font-weight: 800;
            color: #1b5e20;
            line-height: 1;
            position: relative;

            &::after {
                content: '';
                position: absolute;
                bottom: -6px;
                left: 50%;
                transform: translateX(-50%);
                width: 50%;
                height: 2px;
                background: rgba(27, 94, 32, 0.3);
                border-radius: 2px;
            }
        }

        .rate {
            font-size: 40px;
            font-weight: 800;
            color: #212121;
            margin-right: 4px;
        }

        .rate-symbol {
            font-size: 20px;
            color: #424242;
        }

        .condition {
            font-size: 14px;
            color: #555;
            background: rgba(51, 51, 51, 0.08);
            padding: 4px 10px;
            border-radius: 4px;
            margin-top: 8px;
            display: inline-block;
        }
    }

    .valid-date {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        color: #616161;
        font-size: 14px;
        margin-top: 15px;
        padding: 8px 12px;
        background: rgba(97, 97, 97, 0.05);
        border-radius: 6px;

        .el-icon-time {
            font-size: 16px;
        }
    }
}

.coupon-footer {
    padding: 0 20px 20px;

    .el-progress {
        margin-bottom: 10px;

        ::v-deep.el-progress-bar__outer {
            border-radius: 4px;
        }

        ::v-deep.el-progress-bar__inner {
            background-color: #81c784;
        }
    }

    .grab-button {
        height: 44px;
        font-size: 16px;
        letter-spacing: 0.5px;
        border-radius: 6px;
        transition: all 0.3s;
        background-color: #4caf50;
        color: white;

        &:hover:not(.is-disabled) {
            transform: scale(1.03);
            box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
        }

        .remaining-count {
            font-size: 14px;
            opacity: 0.8;
            margin-left: 6px;
        }
    }
}

@keyframes gentleVibrate {
    0% {
        transform: translateX(0);
    }

    25% {
        transform: translateX(-3px);
    }

    50% {
        transform: translateX(3px);
    }

    75% {
        transform: translateX(-3px);
    }

    100% {
        transform: translateX(0);
    }
}
</style>